'use client';

import React, { useState } from 'react';
import {
  List,
  ListItem,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Collapse,
  IconButton,
  Tooltip,
  Typography,
} from '@mui/material';
import { ExpandLess, ExpandMore } from '@mui/icons-material';
import { SubMenu } from '@/app/_data/menu-data';
import Link from 'next/link';

interface SideMenuProps {
  submenus: SubMenu[];
  isCollapsed: boolean;
}

const SideMenu: React.FC<SideMenuProps> = ({ submenus, isCollapsed }) => {
  const [open, setOpen] = useState<string | null>(null);

  const handleClick = (id: string) => {
    setOpen(open === id ? null : id);
  };

  const renderMenuItem = (item: SubMenu) => (
    <React.Fragment key={item.id}>
      <Tooltip title={isCollapsed ? item.label : ''} placement="right">
        <ListItem disablePadding sx={{ display: 'flex' }}>
          <ListItemButton
            component={Link}
            href={item.path}
            sx={{ justifyContent: isCollapsed ? 'center' : 'initial', flex: 1 }}
          >
            {item.icon && <ListItemIcon sx={{ minWidth: 0, mr: isCollapsed ? 'auto' : 3, justifyContent: 'center' }}>{item.icon}</ListItemIcon>}
            <ListItemText primary={item.label} sx={{ opacity: isCollapsed ? 0 : 1 }} />
          </ListItemButton>
          {item.children && (
            <IconButton
              onClick={() => handleClick(item.id)}
              size="small"
              sx={{ display: isCollapsed ? 'none' : 'inline-flex' }}
            >
              {open === item.id ? <ExpandLess /> : <ExpandMore />}
            </IconButton>
          )}
        </ListItem>
      </Tooltip>
      {!isCollapsed && item.children && (
        <Collapse in={open === item.id} timeout="auto" unmountOnExit>
          <List component="div" disablePadding sx={{ pl: 4 }}>
            {item.children.map(renderMenuItem)}
          </List>
        </Collapse>
      )}
    </React.Fragment>
  );

  return (
    <List>
      <Typography variant="h6" sx={{ textAlign: 'center', my: 2, opacity: isCollapsed ? 0 : 1 }}>
        Logo position
      </Typography>
      {submenus.map(renderMenuItem)}
    </List>
  );
};

export default SideMenu;